Skip to content

feat: clearing library#357

Merged
bekauz merged 20 commits into
mainfrom
benskey/clearing-library
May 26, 2025
Merged

feat: clearing library#357
bekauz merged 20 commits into
mainfrom
benskey/clearing-library

Conversation

@bekauz

@bekauz bekauz commented May 23, 2025

Copy link
Copy Markdown
Contributor

closes #350

Description

Introduces the clearing queue library.

This library allows registering and settling obligations.

Sender validation

Any message sender validations are expected to be done on authorizations level.

Obligation registration

Obligations are registered with the following execute msg variant:

/// validates and enqueues a new withdrawal obligation
RegisterObligation {
    /// where the payout is to be routed
    recipient: String,
    /// what is owed to the recipient
    payout_coins: Vec<Coin>,
    /// some unique identifier for the request
    id: Uint64,
},

In turn, the following validations are performed:

  1. obligation id was not registered before
  2. payout_coins vector is not empty
  3. every coin in payout_coins amount is non-zero
  4. recipient address is valid

Following the validations, the constructed obligation is pushed to the end of the queue,
and store the obligation id to prevent double accounting.

From here, the validation is considered valid and ready to be settled.

Obligation settlement

Obligations are settled with the following execute msg variant:

/// settles the oldest withdrawal obligation
SettleNextObligation {},

In turn, the following validations are performed:

  1. obligation queue has at least one element
  2. settlement input account has sufficient funds for settling every coin to be paid out

After that, a BankSend message is constructed and delegated to be executed on behalf
of the settlement (input) account.

Summary by CodeRabbit

  • New Features

    • Added the Valence Clearing Queue library to manage withdrawal obligations in a FIFO queue with registration and settlement capabilities.
    • Configurable settlement input account ensures funds are available before obligation settlement.
    • Supports querying queue information, obligations, and obligation status for transparency and testing.
  • Documentation

    • Added detailed documentation and README outlining library usage, configuration, and interaction flow.
  • Tests

    • Implemented extensive tests covering registration validation, settlement requirements, queue ordering, multi-user and multi-denomination scenarios, and error conditions.

@bekauz bekauz requested a review from keyleu May 23, 2025 16:29
@coderabbitai

coderabbitai Bot commented May 23, 2025

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

A new clearing queue library has been added, including a CosmWasm contract, message and state definitions, configuration, testing suite, and documentation. The contract manages withdrawal obligations in a FIFO queue, validating inputs, maintaining state, and executing settlements from a designated input account.

Changes

File(s) Change Summary
Cargo.toml Added valence-clearing-queue as a workspace dependency with the "library" feature.
contracts/libraries/clearing-queue/Cargo.toml, .cargo/config.toml, README.md Added manifest, Cargo config (with command aliases), and documentation for the new clearing queue library.
contracts/libraries/clearing-queue/src/lib.rs, contract.rs, msg.rs, state.rs Implemented the clearing queue contract, message types, state management, and library module declarations.
contracts/libraries/clearing-queue/src/testing/builder.rs, suite.rs, mod.rs, tests.rs Added a builder, test suite, test module declarations, and comprehensive tests for the clearing queue contract.
docs/src/SUMMARY.md, docs/src/libraries/cosmwasm/clearing_queue.md Added documentation entry and detailed documentation for the clearing queue library.
contracts/libraries/clearing-queue/schema/valence-clearing-queue.json Added comprehensive JSON schema defining instantiate, execute, and query message formats and responses.
contracts/libraries/clearing-queue/src/bin/schema.rs Added schema generation binary for contract API message types.

Sequence Diagram(s)

sequenceDiagram
    participant Strategist
    participant ClearingQueueContract
    participant SettlementAccount
    participant Recipient

    Strategist->>ClearingQueueContract: RegisterObligation(recipient, payout, id)
    ClearingQueueContract->>ClearingQueueContract: Validate & enqueue obligation

    Strategist->>ClearingQueueContract: SettleNextObligation()
    ClearingQueueContract->>ClearingQueueContract: Pop oldest obligation
    ClearingQueueContract->>SettlementAccount: Check balance for payout
    alt Sufficient funds
        ClearingQueueContract->>SettlementAccount: BankSend(payout to recipient)
        SettlementAccount->>Recipient: Transfer coins
    else Insufficient funds
        ClearingQueueContract->>Strategist: Error (insufficient funds)
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Accept incoming withdrawal obligations and store in a FIFO queue (#350) The contract implements registration and storage of obligations in a FIFO queue.
Allow authorized strategist to settle oldest items in the queue (#350) The SettleNextObligation function pops and settles the oldest obligation.
RegisterObligation: Validate source and recipient address, push to queue if valid (#350) Validation occurs during registration, and obligations are enqueued accordingly.
Settlement: Pop head, validate settlement account balance, delegate payout via BankSend (#350) Settlement process checks balance and executes transfer via BankSend.
Explicitly separate settlement logic from liquidity management (funding is out of scope) (#350) The contract handles only settlement, with funding outside its scope.

Possibly related PRs

  • feat: clearing library #357: Introduces the same clearing queue library with identical contract modules, message types, state management, testing infrastructure, and documentation in the workspace.

Suggested reviewers

  • keyleu

Poem

In the warren, queues are neat,
Obligations line up for a treat.
With input coins and FIFO flow,
Each payout hops where it must go.
Strategists settle, rabbits cheer—
The clearing queue is finally here!
🥕✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c7bfa24 and f2a4881.

📒 Files selected for processing (5)
  • contracts/libraries/clearing-queue/schema/valence-clearing-queue.json (1 hunks)
  • contracts/libraries/clearing-queue/src/bin/schema.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/contract.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/msg.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/suite.rs (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
Cargo.toml (1)

93-93: Maintain logical ordering of workspace dependencies.

The new valence-clearing-queue entry should be grouped consistently with other contracts/libraries/* dependencies—ideally in alphabetical order. Consider moving it before valence-supervaults-withdrawer to keep the list organized.

Apply this diff to reorder:

- valence-supervaults-withdrawer       = { path = "contracts/libraries/supervaults-withdrawer", features = ["library"] }
- valence-clearing-queue               = { path = "contracts/libraries/clearing-queue", features = ["library"] }
+ valence-clearing-queue               = { path = "contracts/libraries/clearing-queue", features = ["library"] }
+ valence-supervaults-withdrawer       = { path = "contracts/libraries/supervaults-withdrawer", features = ["library"] }
contracts/libraries/clearing-queue/src/state.rs (1)

27-27: Fix typo in field name.

The field name enque_block should be enqueue_block for correct English spelling.

-    pub enque_block: BlockInfo,
+    pub enqueue_block: BlockInfo,
docs/src/libraries/cosmwasm/clearing_queue.md (1)

6-6: Apply style improvements for better readability.

The static analysis tools have identified valid style improvements that would make the documentation more concise.

-> This library functions solely as a settlement engine. The settlement account funding (liquidity-management) flow is outside of its scope and is managed by a strategist. This management process likely involves monitoring both the settlement account balance and the obligation queue in order to ensure the settlement account maintains sufficient liquidity for obligation settlements.
+> This library functions solely as a settlement engine. The settlement account funding (liquidity-management) flow is outside its scope and is managed by a strategist. This management process likely involves monitoring both the settlement account balance and the obligation queue to ensure the settlement account maintains sufficient liquidity for obligation settlements.
🧰 Tools
🪛 LanguageTool

[style] ~6-~6: This phrase is redundant. Consider using “outside”.
Context: ... funding (liquidity-management) flow is outside of its scope and is managed by a strategis...

(OUTSIDE_OF)


[style] ~6-~6: Consider a more concise word here.
Context: ...ccount balance and the obligation queue in order to ensure the settlement account maintains...

(IN_ORDER_TO_PREMIUM)

contracts/libraries/clearing-queue/src/testing/builder.rs (1)

79-84: Remove debug print statement

The println! statement should be removed from test code. Use proper logging if needed.

 pub fn with_input_balances(mut self, input_coins: Vec<Coin>) -> Self {
     self.input_balances = input_coins;
-    println!("input balances = {:?}", self.input_balances);
     self
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f42eabb and 38ef270.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • Cargo.toml (1 hunks)
  • contracts/libraries/clearing-queue/.cargo/config.toml (1 hunks)
  • contracts/libraries/clearing-queue/Cargo.toml (1 hunks)
  • contracts/libraries/clearing-queue/README.md (1 hunks)
  • contracts/libraries/clearing-queue/src/contract.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/lib.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/msg.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/state.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/builder.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/mod.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/suite.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/tests.rs (1 hunks)
  • docs/src/SUMMARY.md (1 hunks)
  • docs/src/libraries/cosmwasm/clearing_queue.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/src/libraries/cosmwasm/clearing_queue.md

[style] ~6-~6: This phrase is redundant. Consider using “outside”.
Context: ... funding (liquidity-management) flow is outside of its scope and is managed by a strategis...

(OUTSIDE_OF)


[style] ~6-~6: Consider a more concise word here.
Context: ...ccount balance and the obligation queue in order to ensure the settlement account maintains...

(IN_ORDER_TO_PREMIUM)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-and-deploy
  • GitHub Check: setup-local-ic
🔇 Additional comments (39)
docs/src/SUMMARY.md (1)

32-32:

Details

✅ Verification successful

Verify the documentation file path.

Ensure that the Clearing Queue entry at line 32 points to an existing file and avoids broken links:

  • The path should be docs/src/libraries/cosmwasm/clearing_queue.md.
  • Confirm the file name matches exactly (including underscores).

🏁 Script executed:

#!/bin/bash
# Verify that the linked documentation file exists
if [ ! -f docs/src/libraries/cosmwasm/clearing_queue.md ]; then
  echo "Error: docs/src/libraries/cosmwasm/clearing_queue.md not found"
  exit 1
fi

Length of output: 62


Confirmed: Clearing Queue documentation link is valid

The file docs/src/libraries/cosmwasm/clearing_queue.md exists and matches the link in docs/src/SUMMARY.md, so the path is correct.

contracts/libraries/clearing-queue/.cargo/config.toml (1)

1-3: Approve Cargo aliases for build and schema.

The [alias] section defines convenient shortcuts for building the WASM binary and generating the schema, consistent with other libraries in the workspace.

contracts/libraries/clearing-queue/src/testing/mod.rs (1)

1-3: Testing module structure looks correct.

The builder and suite modules are public for test utilities, and the private tests module groups test cases. All are scoped under testing in lib.rs with #[cfg(test)], ensuring they are only compiled during tests.

contracts/libraries/clearing-queue/src/lib.rs (2)

1-4: Public API modules defined appropriately.

The contract, msg, and state modules expose the core clearing queue logic, message types, and state management. No visibility or import issues detected here.


5-6: Test harness inclusion is correct.

The #[cfg(test)] mod testing; ensures that all test utilities and cases in testing/ are only compiled for test builds. This aligns with Rust best practices.

contracts/libraries/clearing-queue/Cargo.toml (1)

1-31: LGTM! Well-structured package configuration.

The Cargo.toml follows CosmWasm best practices with proper workspace inheritance, appropriate crate types for both library and binary usage, and a sensible "library" feature flag for conditional compilation. The dependencies are well-chosen for a CosmWasm smart contract library.

contracts/libraries/clearing-queue/README.md (1)

1-37: Excellent documentation with clear flow visualization.

The README provides comprehensive coverage of the clearing queue library's purpose and functionality. The mermaid diagram effectively illustrates the interaction flow between components, and the configuration section clearly explains the settlement input account concept.

contracts/libraries/clearing-queue/src/state.rs (1)

1-16: Good state design for FIFO queue management.

The state structures are well-designed for managing a clearing queue system. Using a separate map for tracking registered obligation IDs effectively prevents duplicate processing, and the QueueMap provides proper FIFO semantics.

docs/src/libraries/cosmwasm/clearing_queue.md (1)

1-47: Comprehensive documentation with minor style improvements needed.

The documentation provides excellent coverage of the clearing queue library's functionality, including a helpful function table and clear configuration examples. The separation of concerns between settlement and liquidity management is well-explained.

🧰 Tools
🪛 LanguageTool

[style] ~6-~6: This phrase is redundant. Consider using “outside”.
Context: ... funding (liquidity-management) flow is outside of its scope and is managed by a strategis...

(OUTSIDE_OF)


[style] ~6-~6: Consider a more concise word here.
Context: ...ccount balance and the obligation queue in order to ensure the settlement account maintains...

(IN_ORDER_TO_PREMIUM)

contracts/libraries/clearing-queue/src/testing/builder.rs (4)

1-15: LGTM!

The imports and test user constants are appropriate for the testing environment.


16-48: LGTM!

The builder struct and trait implementation follow the delegation pattern correctly.


86-89: LGTM!

Using Addr::unchecked is acceptable in test code where we control the inputs.


91-129: LGTM!

The build method correctly sets up the test environment with proper initialization logic.

contracts/libraries/clearing-queue/src/contract.rs (6)

1-15: LGTM!

Standard CosmWasm imports and proper use of environment variables for contract metadata.


16-41: LGTM!

Entry points correctly delegate to the base library implementation.


43-57: LGTM!

Config update correctly delegates to the configuration update logic.


86-137: LGTM!

Comprehensive validation and proper storage of withdrawal obligations. Good use of ensure! macros for validation.


139-182: LGTM!

Settlement logic correctly validates balances and executes transfers with proper authorization.


184-236: LGTM!

Query implementations are correct with proper pagination support for obligations.

contracts/libraries/clearing-queue/src/testing/suite.rs (3)

1-15: LGTM!

Test imports and denomination constants are appropriate.


26-80: LGTM!

Test helper methods provide clean abstractions for contract interactions.


82-126: LGTM!

Query methods and trait implementation correctly delegate to the inner test suite.

contracts/libraries/clearing-queue/src/testing/tests.rs (10)

1-12: LGTM! Well-organized imports and constants.

The imports are appropriate for CosmWasm testing, and the INVALID_ADDR constant provides a reusable invalid address for validation tests.


14-34: LGTM! Comprehensive address validation testing.

These tests properly verify that invalid addresses are rejected during both instantiation and configuration updates, with appropriate error message validation.


36-62: LGTM! Essential settlement precondition validation.

These tests properly verify critical settlement preconditions:

  • Empty queue protection prevents invalid operations
  • Insufficient funds checking prevents failed settlements with specific error messages including denomination details

64-96: LGTM! Thorough obligation registration validation.

These tests comprehensively validate obligation registration requirements:

  • Non-empty payout coins enforcement
  • Valid recipient address validation
  • Non-zero coin amount validation with specific denomination error messages

98-117: LGTM! Essential happy path validation.

This test properly verifies the basic obligation registration flow, checking both queue metadata (count) and actual obligation list contents.


119-170: LGTM! Excellent FIFO queue behavior validation.

This test comprehensively validates the FIFO queue mechanics:

  • Verifies correct ordering when multiple obligations are registered
  • Confirms that settlement processes the oldest obligation first
  • Tests both queue metadata and obligation ordering before/after settlement

172-201: LGTM! Critical duplicate prevention security testing.

These tests validate essential security features:

  • Prevention of duplicate obligation IDs during registration
  • Ensuring obligation IDs remain permanently reserved even after settlement

This prevents double-accounting attacks and maintains system integrity.


203-239: LGTM! Comprehensive multi-denomination settlement testing.

This test thoroughly validates settlement with multiple coin denominations:

  • Verifies correct balance deduction from input account for each denomination
  • Confirms proper credit to user account for each denomination
  • Tests the complete settlement flow for complex obligations

241-283: LGTM! Thorough multi-user settlement validation.

This test comprehensively validates settlement across multiple users:

  • Verifies correct FIFO processing for different users
  • Ensures proper balance accounting for each user
  • Confirms total input account balance reduction matches settled amounts

285-323: LGTM! Complete multi-denomination obligation testing.

This test validates complex settlement scenarios:

  • Multiple obligations for the same user with different denominations
  • Independent denomination tracking and settlement
  • Proper balance accounting per denomination across settlements
contracts/libraries/clearing-queue/src/msg.rs (7)

1-9: LGTM! Appropriate imports for CosmWasm library messaging.

All necessary dependencies are included for schema generation, validation, error handling, and library interface functionality.


11-25: LGTM! Well-designed configuration structures.

Clear separation between input configuration (LibraryConfig) and validated configuration (Config) with appropriate types:

  • LibraryAccountType for flexible input handling
  • Addr for validated addresses
  • Clear documentation explaining the settlement account purpose

27-40: LGTM! Well-structured execute messages for queue operations.

The message design is appropriate:

  • RegisterObligation includes all necessary parameters (recipient, payout, unique ID)
  • SettleNextObligation is parameter-free, correctly implementing FIFO processing
  • Good documentation explaining each message's purpose

42-55: LGTM! Clean configuration API with proper validation.

The implementation provides:

  • Convenient constructor with flexible input type conversion
  • Centralized validation logic in do_validate()
  • Proper error handling returning LibraryError

57-68: LGTM! Proper validation trait implementation.

Correctly implements the library validation pattern:

  • Conditional compilation for non-wasm pre_validate()
  • Reuses centralized validation logic
  • Returns validated Config with proper error handling

70-82: LGTM! Proper configuration update handling.

The implementation correctly handles optional configuration updates:

  • Loads existing configuration from storage
  • Updates only specified fields (using Option for selective updates)
  • Proper error handling and storage operations

Note: LibraryConfigUpdate appears to be generated by the ValenceLibraryInterface macro on LibraryConfig.


84-115: LGTM! Comprehensive query interface for queue operations.

Well-designed query system:

  • QueueInfo provides essential metadata (count, pagination indices)
  • Obligations query supports range-based retrieval for scalability
  • Response structures include all necessary fields
  • Proper use of query macros for schema generation

@keyleu keyleu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current implementation works, left some suggestions for state refactor that would allow more queries to know what's going on and what happened.

Comment thread contracts/libraries/clearing-queue/README.md Outdated
Comment thread docs/src/libraries/cosmwasm/clearing_queue.md Outdated
Comment thread contracts/libraries/clearing-queue/src/msg.rs
/// end index
to: Option<u64>,
},
}

@keyleu keyleu May 26, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add a query to see if a withdrawal_request is already registered. I see this being useful to check if we need to get a proof for a specific ID.
Or maybe a query that returns a withdrawal_request for an ID and returns None if it doesn't exist or something like that

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my thinking was that this could be done on frontend by filtering the ObligationsResponse as strategist shouldn't be concerned with individual requests

@keyleu keyleu May 26, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm just thinking of the logic the strategist will use to request a proof. How can he know the ID that he needs to request a proof for? I guess he could fetch the current withdraw request on Ethereum and start going down from there and check if they are registered until he finds one that isnt?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if strategist should be touching neutron for proof generation. feels a bit fragile given the latency of the coprocessor?

@keyleu keyleu May 26, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's say the clearing queue is empty. And the strategist restarts. How does it know which ID to use to start asking for proofs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I think this problem applies not just in situations where strategist restarts but also in cases where withdraw obligations get posted out of order.

tbh I don't have a good answer because I don't know the internals of the coprocessor. hence the decoupled design of this contract - I assumed that coprocessor + strategist + ethereum state is sufficient to shield the settlement flow from the way those requests originate (other than the withdraw obligation id checks).

cc @hxrts

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coprocessor has no state. Will only proof that a certain ID exists and give the necessary information to this contract.
We can make the strategist post the obligations always in order, but for that it needs to at least know the last one posted, currently we have no way of knowing the last posted because the clearing queue might be empty and we have no access to the other map via a query

Comment thread contracts/libraries/clearing-queue/src/state.rs
Comment on lines +6 to +8
/// set of registered obligation ids meant to prevent double filling
/// of any given obligation
pub const REGISTERED_OBLIGATION_IDS: Map<u64, Empty> = Map::new("reg_obl_id");

@keyleu keyleu May 26, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So currently we can only know what withdrawal obligations are currently being processed (currently in the queue), and these are currently not queriable by address.

I suggest changing this REGISTERED_OBLIGATIONS_IDS into an IndexedMap with a MultiIndex (request_addr, which would need to be added to WithdrawalObligation, along with the status, which would need to be updated after being processed).
This way we can query:

  • Withdrawal obligation for a specific ID.
  • Withdrawal obligations per request address. For this query we would get all withdrawal obligations that an eth address requested along with their current status.

This would be enough in case the front end would like to display this information for a user. Otherwise we don't really know much of what happened to withdrawal obligations because once they are processed they are just gone

LMK what you think.

We can of course rely only on indexing transactions on ethereum but since storing this on Neutron is so cheap anyways I don't see why not

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this kind of follows from my request above.

happy to jam on this if you feel like it's worthwhile, but in the current design request_addr would be purely informational and useful only for frontend as it has no impact on the settlements

@keyleu keyleu May 26, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, let's talk about this. The minimum we need here is a query on this Map here for us to know if something is pending to be registered or not. Otherwise we can't know if something hasn't been registered yet or is completed. That's the bare minimum, rest would just be extras to make it easier

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
docs/src/libraries/cosmwasm/clearing_queue.md (2)

5-7: Refine wording for clarity and conciseness.

Reduce redundancy by replacing "outside of its scope" with "outside its scope" and "in order to ensure" with "to ensure".

- > This library functions solely as a settlement engine. The settlement account funding (liquidity-management) flow is outside of its scope and is managed by a strategist. This management process likely involves monitoring both the settlement account balance and the obligation queue in order to ensure the settlement account maintains sufficient liquidity for obligation settlements.
+ > This library functions solely as a settlement engine. The settlement account funding (liquidity-management) flow is outside its scope and is managed by a strategist. This management process likely involves monitoring both the settlement account balance and the obligation queue to ensure the settlement account maintains sufficient liquidity for obligation settlements.
🧰 Tools
🪛 LanguageTool

[style] ~6-~6: This phrase is redundant. Consider using “outside”.
Context: ... funding (liquidity-management) flow is outside of its scope and is managed by a strategis...

(OUTSIDE_OF)


[style] ~6-~6: Consider a more concise word here.
Context: ...ccount balance and the obligation queue in order to ensure the settlement account maintains...

(IN_ORDER_TO_PREMIUM)


29-33: Consider adding a usage example.

Providing a Rust code snippet that demonstrates instantiating the library, registering an obligation, and settling the next obligation would help users quickly understand the API and integration points.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 38ef270 and a71d9e8.

📒 Files selected for processing (6)
  • contracts/libraries/clearing-queue/README.md (1 hunks)
  • contracts/libraries/clearing-queue/src/contract.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/msg.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/suite.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/tests.rs (1 hunks)
  • docs/src/libraries/cosmwasm/clearing_queue.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/libraries/clearing-queue/src/msg.rs
🧰 Additional context used
🪛 LanguageTool
docs/src/libraries/cosmwasm/clearing_queue.md

[style] ~6-~6: This phrase is redundant. Consider using “outside”.
Context: ... funding (liquidity-management) flow is outside of its scope and is managed by a strategis...

(OUTSIDE_OF)


[style] ~6-~6: Consider a more concise word here.
Context: ...ccount balance and the obligation queue in order to ensure the settlement account maintains...

(IN_ORDER_TO_PREMIUM)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: setup-local-ic
  • GitHub Check: build-and-deploy
🔇 Additional comments (11)
contracts/libraries/clearing-queue/README.md (1)

1-37: Excellent documentation with clear system overview.

The README provides a comprehensive overview of the clearing queue library with:

  • Clear explanation of FIFO queue semantics for withdrawal obligations
  • Well-designed mermaid diagram illustrating the system flow
  • Proper documentation of the configuration structure
  • Clear explanation of settlement account validation

The documentation aligns well with the implementation and provides good guidance for users.

contracts/libraries/clearing-queue/src/contract.rs (4)

16-24: Well-structured instantiate function.

The instantiate function properly delegates to the library base, maintaining consistency with the framework architecture.


86-137: Comprehensive obligation registration validation.

The registration function implements robust validation:

  • Prevents duplicate obligation IDs (lines 95-100)
  • Validates non-empty payout coins (lines 103-108)
  • Ensures non-zero coin amounts (lines 111-119)
  • Validates recipient address format (line 122)
  • Maintains both queue and ID tracking for consistency

The error messages are clear and informative for debugging.


139-181: Secure settlement implementation with proper validation.

The settlement function ensures safety through:

  • FIFO queue processing (line 141)
  • Empty queue error handling (lines 143-150)
  • Settlement account balance validation for each coin (lines 157-167)
  • Proper fund transfer execution using execute_on_behalf_of (line 178)

This prevents failed transactions due to insufficient funds and maintains queue integrity.


211-234: Complete query interface implementation.

The query functions provide comprehensive access to:

  • Contract ownership and processor information
  • Library configuration (both validated and raw)
  • Queue state and obligations with range support

This enables proper monitoring and debugging capabilities.

contracts/libraries/clearing-queue/src/testing/suite.rs (2)

16-80: Well-designed testing suite with comprehensive functionality.

The testing suite provides excellent coverage with:

  • Clear methods for registering obligations and settlement operations
  • Proper configuration update functionality
  • Comprehensive query methods for balance and queue state validation
  • Clean error handling using AnyResult

The method signatures are intuitive and support thorough integration testing.


102-126: Proper trait implementation for framework integration.

The LibraryTestSuite trait implementation correctly delegates to the inner suite, maintaining consistency with the testing framework while exposing necessary functionality for clearing queue testing.

contracts/libraries/clearing-queue/src/testing/tests.rs (4)

14-96: Excellent input validation test coverage.

The validation tests comprehensively cover all input validation scenarios:

  • Invalid addresses during instantiation and updates (lines 14-34)
  • Empty queue settlement attempts (lines 36-42)
  • Insufficient settlement account balance (lines 44-62)
  • Empty payout coins and invalid recipient addresses (lines 64-86)
  • Zero amount validation (lines 88-96)

Each test uses precise error message matching for accurate validation.


119-170: Thorough FIFO queue behavior validation.

This test excellently verifies the First-In-First-Out queue semantics:

  • Registers obligations in a specific order (user_1 → user_3 → user_2)
  • Validates queue state before and after operations
  • Confirms that settlement processes the oldest obligation first
  • Verifies remaining queue order after settlement

This is critical for ensuring the queue operates correctly under various scenarios.


172-201: Critical duplicate ID prevention testing.

These tests ensure the important security feature of preventing duplicate obligation processing:

  • Tests immediate duplicate registration (lines 172-183)
  • Tests duplicate registration after settlement (lines 185-201)
  • Validates that obligation IDs remain blocked even after fulfillment

This prevents double-spending and maintains system integrity.


203-323: Comprehensive balance and settlement verification.

The multi-denomination and multi-user tests provide excellent coverage:

  • Validates balance updates for multiple denominations (lines 203-239)
  • Tests multiple user settlements with proper balance tracking (lines 241-283)
  • Verifies cross-denomination settlement accuracy (lines 285-323)

These tests ensure the settlement mechanism works correctly across complex scenarios and properly updates all account balances.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
contracts/libraries/clearing-queue/src/contract.rs (2)

139-183: Consider potential race conditions in balance validation.

The settlement logic is well-structured, but there's a potential race condition between balance checking and execution:

  1. Race condition: The balance is checked for each coin (lines 157-168), but the actual transfer happens later via execute_on_behalf_of. If other transactions modify the settlement account balance between the check and execution, the transfer could fail.

  2. Error handling: The current implementation will fail the entire settlement if any coin has insufficient balance, which is appropriate.

Consider one of these approaches to handle the race condition:

  1. Accept the risk: Document that settlement can fail if balance changes between check and execution
  2. Atomic validation: Move balance checking to the settlement account's logic if possible
  3. Retry mechanism: Implement a retry mechanism for failed settlements

The current implementation is acceptable for most use cases, but the race condition should be documented.


69-84: Suggest adding queue size limits for DoS protection.

The function routing is clean, but consider adding queue size limits to prevent potential DoS attacks through unlimited obligation registration.

Consider adding a maximum queue size check in the registration function:

fn try_register_withdraw_obligation(
    deps: DepsMut,
    env: Env,
-   _cfg: Config,
+   cfg: Config,
    recipient: String,
    payout_coins: Vec<Coin>,
    id: Uint64,
) -> Result<Response, LibraryError> {
+   // Check queue size limit (if configured)
+   if let Some(max_size) = cfg.max_queue_size {
+       let current_size = CLEARING_QUEUE.len(deps.storage)?;
+       ensure!(
+           current_size < max_size,
+           LibraryError::ExecutionError("queue size limit exceeded".to_string())
+       );
+   }

This would require adding max_queue_size: Option<u64> to the Config struct.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a71d9e8 and fa49916.

📒 Files selected for processing (2)
  • contracts/libraries/clearing-queue/src/contract.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/msg.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/libraries/clearing-queue/src/msg.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: solidity contracts
  • GitHub Check: setup-local-ic
  • GitHub Check: build-and-deploy
🔇 Additional comments (5)
contracts/libraries/clearing-queue/src/contract.rs (5)

1-15: LGTM! Standard CosmWasm contract setup.

The imports and constants follow standard CosmWasm patterns. Using environment variables for contract name and version is a good practice for build-time configuration.


16-24: LGTM! Clean instantiate function.

The instantiate function properly delegates to the valence_library_base, which handles standard initialization including version info and configuration setup.


26-41: LGTM! Proper execute function delegation.

The execute function correctly routes to the base library with custom handlers for function processing and config updates.


193-208: LGTM! Clean query implementation.

The query functions are well-implemented with proper error handling and use standard CosmWasm query patterns.


211-234: LGTM! Comprehensive query routing.

The query entry point properly handles all query types including standard valence library queries and custom clearing queue queries.

Comment thread contracts/libraries/clearing-queue/src/contract.rs
@bekauz bekauz requested a review from keyleu May 26, 2025 13:19

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
contracts/libraries/clearing-queue/src/msg.rs (2)

91-93: Consider past feedback about QueueInfo query design.

From previous review comments, there was feedback about the QueueInfo query returning a struct with just a length field instead of returning a simple u64. While the current design provides extensibility for future fields, consider if the simpler approach would be more appropriate.


106-108: ObligationStatus query addresses past concerns about ID tracking.

The ObligationStatus query provides the ability to check if a specific obligation is settled, which partially addresses past review concerns about knowing which IDs need proof generation. However, the broader concern about strategist restart scenarios and out-of-order obligation posting may still need consideration at the architecture level.

🧹 Nitpick comments (1)
contracts/libraries/clearing-queue/src/msg.rs (1)

36-36: Consider using a more specific type for obligation ID.

Using Uint64 for the obligation ID is functional, but consider if a more domain-specific type or newtype wrapper would provide better type safety and clarity about the ID's purpose and constraints.

-        id: Uint64,
+        id: u64,

This would be more idiomatic Rust and align with the query interface that uses u64.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa49916 and c7bfa24.

📒 Files selected for processing (5)
  • contracts/libraries/clearing-queue/src/contract.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/msg.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/state.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/suite.rs (1 hunks)
  • contracts/libraries/clearing-queue/src/testing/tests.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/libraries/clearing-queue/src/state.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build
  • GitHub Check: setup-local-ic
  • GitHub Check: build-and-deploy
🔇 Additional comments (8)
contracts/libraries/clearing-queue/src/testing/tests.rs (1)

1-341: Excellent comprehensive test coverage with well-structured test cases.

The test suite demonstrates thorough coverage of the clearing queue functionality including:

  • Input validation (addresses, payout coins, amounts)
  • Queue behavior verification (FIFO ordering)
  • Settlement mechanics (balance checks, fund transfers)
  • Error conditions (empty queue, insufficient funds, duplicate registrations)
  • Multi-user and multi-denomination scenarios

The tests are well-organized with clear naming conventions and appropriate use of #[should_panic] for error conditions. The builder pattern usage makes test setup clean and maintainable.

contracts/libraries/clearing-queue/src/contract.rs (4)

101-106: Proper validation prevents double registration.

The check to ensure obligation IDs are not already registered is essential for preventing double settlement. The error message is clear and informative.


117-125: Thorough validation of payout coins.

The validation ensures each coin has a non-zero amount with clear error messages including the problematic denomination. This prevents invalid obligations from being registered.


165-181: Robust balance validation before settlement.

The settlement logic properly validates that the settlement account has sufficient balance for each denomination before attempting transfer. This prevents partial settlements and provides clear error messages when funds are insufficient.


183-196: Secure fund transfer implementation.

The settlement logic correctly:

  1. Constructs bank send messages with validated amounts
  2. Uses execute_on_behalf_of to transfer from settlement account
  3. Updates obligation status to prevent double settlement
  4. Returns appropriate response
contracts/libraries/clearing-queue/src/testing/suite.rs (3)

26-48: Clean obligation registration test helper.

The method properly constructs the execute message and handles the conversion from u64 to Uint64 for the ID parameter. The error propagation is appropriate for test scenarios.


82-107: Comprehensive query helper methods.

The query methods provide good coverage for testing different aspects of the contract state:

  • Account balances for settlement verification
  • Queue information for length checking
  • Obligation status for settlement verification
  • Obligations list for FIFO order verification

109-133: Proper delegation to inner test suite.

The LibraryTestSuite trait implementation correctly delegates all methods to the inner suite, maintaining the testing framework's interface while adding domain-specific functionality.

Comment thread contracts/libraries/clearing-queue/src/testing/tests.rs
Comment thread contracts/libraries/clearing-queue/src/contract.rs
Comment thread contracts/libraries/clearing-queue/src/contract.rs Outdated
@bekauz bekauz merged commit b1a986b into main May 26, 2025
3 of 4 checks passed
@bekauz bekauz deleted the benskey/clearing-library branch May 26, 2025 14:54
@coderabbitai coderabbitai Bot mentioned this pull request May 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: clearing library

2 participants